import React  from 'react';
import PropTypes from 'proptypes';
import Select from 'react-select';
import Checkbox from './checkbox.jsx';
import Dialog from '@mui/material/Dialog';
import DialogTitle from '@mui/material/DialogTitle';
import DialogContent from '@mui/material/DialogContent';
import DialogActions from '@mui/material/DialogActions';
import Button from '@mui/material/Button';
import FormHelperText from '@mui/material/FormHelperText';
import FormControlLabel from '@mui/material/FormControlLabel';
import FormControl from '@mui/material/FormControl';
import FormLabel from '@mui/material/FormLabel';
import CancelIcon from '@mui/icons-material/Cancel';
import SaveIcon from '@mui/icons-material/Save';
import set from 'lodash/set';
var { shell } = window.myremote.electron;

export default function SettingsModalForm(props){
  // static propTypes = {
  //   onSaveClick: PropTypes.func.isRequired,
  //   onCancelClick: PropTypes.func.isRequired,
  //   config: PropTypes.object,
  //   error: PropTypes.object,
  // };
  const [state,setState]=React.useState({...props.config.data,
      modalOpen: false,});
  //   if (!state.zoomFactor) {
  //     state.zoomFactor = 1;
  //   }
  // }
  console.log("settings-modal=======");
  console.log(props);
  console.log(state);
  
  React.useEffect(()=>{
    if (props.modalOpen){ 
      onShow();
    }else{
      onHide();
    }
  },[props.modalOpen])
  React.useEffect(()=>{
    setState((state)=>({...state,error:props.error}));
  },[props.error])
  // UNSAFE_componentWillReceiveProps(nextProps) {
  //   // console.log(nextProps);
  //   setState({ error: nextProps.error });
  //   if (!props.modalOpen && nextProps.modalOpen) {
  //     onShow();
  //   } else if (props.modalOpen && !nextProps.modalOpen) {
  //     onHide();
  //   }
  // }
  const onShow = () => {};
  const onHide = () => {
    console.log('onHide');
    //props.onCancelClick();
  };

  const onSaveClick = () => {
    props.onSaveClick(mapStateToConfig(state));
  };

  const onDocClick=(event)=>{
    event.preventDefault();
    shell.openExternal(
      'https://github.com/sqlectron/sqlectron-gui/blob/master/docs/app/configuration-file.md'
    );
  }

  const mapStateToConfig=(state) =>{
    const config = {
      zoomFactor: parseFloat(state.zoomFactor) || 1,
      limitQueryDefaultSelectTop:
        parseInt(state.limitQueryDefaultSelectTop, 10) || 100,
      enabledAutoComplete: state.enabledAutoComplete || false,
      enabledLiveAutoComplete: state.enabledLiveAutoComplete || false,
      enabledDarkTheme: state.enabledDarkTheme || false,
    };
    if (!state.log) {
      return config;
    }

    const { log } = state;
    config.log = {
      console: log.console,
      file: log.file,
      level: log.level,
      path: log.path,
    };

    return config;
  }

  const highlightError=(name)=> {
    const { error } = state;
    let hasError = !!(error && error[name]);
    if (error && error.log && /^log\./.test(name)) {
      const logErrors = error.log[0].errors[0];
      const lastName = name.replace(/^log\./, '');
      hasError = !!~Object.keys(logErrors).indexOf(lastName);
    }
    return hasError ? 'error' : '';
  }

  const handleChange=(event)=> {
    const newState = {};
    const { target } = event;
    const value = target.files ? target.files[0].path : target.value;
    const name = target.name.replace(/^file\./, '');
    const [name1, name2] = name.split('.');

    if (name1 && name2) {
      newState[name1] = { ...state[name1] };
    }

    set(newState, name, value);

    // return setState(newState);
    setState((state)=>({...state,...newState}));
  }

  const handleOnLogLevelChange=(level)=> {
    // setState({ log: { ...state.log, level } });
    setState((state)=>({...state,log: { ...state.log, level }}));
  }

  const renderLogLevelItem=({ label, icon }) =>{
    return (
      <span>
        <i className={`icon ${icon}`} /> {label}
      </span>
    );
  }

  const renderActionsPanel=()=> {
    return (
      <div className="actions">
        <Button
          className="small ui black deny right labeled icon button"
          onClick={props.onCancelClick}
          tabIndex={0}
        >
          Cancel
          <CancelIcon />
        </Button>
        <Button
          className="small ui green right labeled icon button"
          tabIndex={0}
          onClick={onSaveClick}
        >
          Save
          <SaveIcon />
        </Button>
      </div>
    );
  }

  const renderSettingsPath=()=> {
    /* eslint max-len:0 */
    return (
      <div className="two fields">
        <div className="field">
          <div className="ui label">
            Path
            <div className="detail">{props.config.path}</div>
          </div>
        </div>
        <div className="field">
          Check out the full settings documentation at{' '}
          <a onClick={onDocClick}>here</a>
        </div>
      </div>
    );
  }

  const renderBasicSettingsPanel=()=> {
    /* eslint max-len:0 */
    // const { zoomFactor } = state;
    //const zoomFactorLabel = `${Math.round(zoomFactor * 100)}%`;
    // console.log("render basic");
    // var zoomFactorClass=highlightError('zoomFactor');
    // console.log(zoomFactorClass);
    return (
      <div>
        <div className="two fields">
          {/*       <div className={`field ${highlightError('zoomFactor')}`}>
            <label>Zoom Factor: {zoomFactorLabel}</label>
            <input
              type="range"
              min="0.4"
              max="3"
              step="0.2"
              name="zoomFactor"
              value={zoomFactor}
              onChange={handleChange}
              style={{ width: '100%', marginTop: '10px' }}
            />
          </div>*/}
          <div
            className={`field ${highlightError(
              'limitQueryDefaultSelectTop'
            )}`}
          >
            <label>Limit of Rows from Select Top Query</label>
            <input
              type="number"
              name="limitQueryDefaultSelectTop"
              value={state.limitQueryDefaultSelectTop || ''}
              onChange={handleChange}
            />
            <p className="help">
              The limit used in the default select from the sidebar context
              menu.
            </p>
          </div>
        </div>

        <div className="three fields">
          <div className="field">
            <Checkbox
              name="enabledAutoComplete"
              label="Auto Complete"
              defaultChecked={state.enabledAutoComplete}
              onChecked={() => setState((state)=>({...state,enabledAutoComplete: true}))}
              onUnchecked={() => setState((state)=>({...state, enabledAutoComplete: false}))}
            />
            <p className="help">
              Enable/Disable auto complete for the query box.
            </p>
          </div>
          <div className="field">
            <Checkbox
              name="enabledLiveAutoComplete"
              label="Live Auto Complete"
              defaultChecked={state.enabledLiveAutoComplete}
              onChecked={() =>setState((state)=>({...state,enabledLiveAutoComplete: true}))} 
              onUnchecked={() =>
                setState((state)=>({...state,enabledLiveAutoComplete: false}))} 
            />
            <p className="help">
              Enable/Disable live auto complete for the query box.
            </p>
          </div>
          <div className="field">
            <Checkbox
              name="enabledDarkTheme"
              label="Dark Theme"
              defaultChecked={state.enabledDarkTheme}
              onChecked={() =>setState((state)=>({...state,enabledDarkTheme: true}))} 
              onUnchecked={() => setState((state)=>({...state,enabledDarkTheme:false}))} 
            />
            <p className="help">Enable/Disable dark theme.</p>
          </div>
        </div>
      </div>
    );
  }

  const renderLoggingSettingsPanel=()=> {
    const log = state.log || {};
    return (
      <div className="ui segment">
        <div className="one field">Logging</div>
        <div>
          <div className="two fields">
            <div className="field">
              <Checkbox
                name="log.console"
                label="Console"
                defaultChecked={log.console}
                onChecked={() =>
                  handleChange({
                    target: { name: 'log.console', value: true },
                  })
                }
                onUnchecked={() =>
                  handleChange({
                    target: { name: 'log.console', value: false },
                  })
                }
              />
              <p className="help">Show logs in the dev tools panel.</p>
            </div>

            <div className="field">
              <Checkbox
                name="log.file"
                label="File"
                defaultChecked={log.file}
                onChecked={() =>
                  handleChange({
                    target: { name: 'log.file', value: true },
                  })
                }
                onUnchecked={() =>
                  handleChange({
                    target: { name: 'log.file', value: false },
                  })
                }
              />
              <p className="help">Save logs into a file.</p>
            </div>
          </div>

          <div className="two fields">
            <div className={`field ${highlightError('log.path')}`}>
              <label>Path</label>
              <div className="ui action input">
                <input
                  type="text"
                  name="log.path"
                  placeholder="~/.sqlectron.log"
                  value={log.path || ''}
                  onChange={handleChange}
                />
                <label
                  htmlFor="file.log.path"
                  className="ui icon button btn-file"
                >
                  <i className="file outline icon" />
                  <input
                    type="file"
                    id="file.log.path"
                    name="file.log.path"
                    onChange={handleChange}
                    style={{ display: 'none' }}
                  />
                </label>
              </div>
              <p className="help">Log file path.</p>
            </div>
            <div
              id="logLevel"
              className={`field ${highlightError('log.level')}`}
            >
              <label>Level</label>
              <Select
                name="log.level"
                options={[
                  { value: 'debug', label: 'Debug', icon: 'bug' },
                  { value: 'info', label: 'Info', icon: 'info' },
                  { value: 'warn', label: 'Warn', icon: 'warning sign' },
                  { value: 'error', label: 'Error', icon: 'remove circle' },
                ]}
                clearable={false}
                onChange={handleOnLogLevelChange}
                optionRenderer={renderLogLevelItem}
                valueRenderer={renderLogLevelItem}
                value={log.level || 'error'}
              />
              <p className="help">Level logging: debug, info, warn, error.</p>
            </div>
          </div>
        </div>
      </div>
    );
  }

    return (
      <Dialog
        id="settings-modal"
        open={props.modalOpen}
        closable="true"
        detachable="false"
        dimmer={'inverted'}
      >
        <DialogTitle>Settings</DialogTitle>
        <DialogContent>
          <form className="ui form">
            {renderBasicSettingsPanel()}
            {renderLoggingSettingsPanel()}
            {renderSettingsPath()}
          </form>
        </DialogContent>
        <DialogActions>{renderActionsPanel()}</DialogActions>
      </Dialog>
    );
}
/*<FormControl component="fieldset" className={classes.formControl}>
          <FormLabel component="legend">Gender</FormLabel>
          <RadioGroup
            aria-label="Gender"
            name="gender1"
            className={classes.group}
            value={state.value}
            onChange={handleChange}
          >
            <FormControlLabel value="female" control={<Radio />} label="Female" />
            <FormControlLabel value="male" control={<Radio />} label="Male" />
            <FormControlLabel value="other" control={<Radio />} label="Other" />
            <FormControlLabel
              value="disabled"
              disabled
              control={<Radio />}
              label="(Disabled option)"
            />
          </RadioGroup>
        </FormControl>
        <FormControl component="fieldset" className={classes.formControl}>
          <FormLabel component="legend">Gender</FormLabel>
          <RadioGroup
            aria-label="gender"
            name="gender2"
            className={classes.group}
            value={state.value}
            onChange={handleChange}
          >
            <FormControlLabel
              value="female"
              control={<Radio color="primary" />}
              label="Female"
              labelPlacement="start"
            />
            <FormControlLabel
              value="male"
              control={<Radio color="primary" />}
              label="Male"
              labelPlacement="start"
            />
            <FormControlLabel
              value="other"
              control={<Radio color="primary" />}
              label="Other"
              labelPlacement="start"
            />
            <FormControlLabel
              value="disabled"
              disabled
              control={<Radio />}
              label="(Disabled option)"
              labelPlacement="start"
            />
          </RadioGroup>
          <FormHelperText>labelPlacement start</FormHelperText>
        </FormControl>*/
